package com.kly.user.serviceImpl.traffic.likeback;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.service.MemberService;
import com.kly.user.db.dao.*;
import com.kly.user.db.entity.*;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.LikeEnum;
import com.kly.user.enums.WLMType;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.task.UserTaskConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public abstract class LikeBackBase {

    public static Log logger = LogFactory.getLog(LikeBackBase.class);

    @Autowired
    UserDao userDao;

    @Resource
    MemberService memberService;

    @Resource
    UserWlmDao userWlmDao;

    @Autowired
    CustomersUserDao customersUserDao;

    @Autowired
    IssueUserDao issueUserDao;


    @Autowired
    UserWlmLogDao userWlmLogDao;

    @Autowired
    IssueLbRecordDao issueLbRecordDao;

    @Autowired

    @Resource
    AsyncEventBus pushEventBus;

    @Autowired
    UserMsgSendTotalDao userMsgSendTotalDao;


    public void dealCondition(IssueConfigEntity issueConfigEntity, UserEntity userEntity) {


    }

    public static boolean isToday(Date date) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        //格式化为相同格式
        return fmt.format(date).toString().equals(fmt.format(new Date()).toString());
    }


    public void push(String userCode, Boolean ifmMember, String app) {
        String toUserCode = null;
        String issueUserCode;
        List<Integer> poolNums = new ArrayList<>();
        if (ifmMember) {
            poolNums.add(2);
            poolNums.add(3);
            poolNums.add(4);
        } else {
            poolNums.add(1);
        }

        CustomersUserEntity customersUserEntity = customersUserDao.getCustomer(userCode);
        if (customersUserEntity == null) {
            issueUserCode = userDao.queryLBIssueUserPool2(userCode, poolNums);
            logger.info("====LikeBackIssueTask-v5:获取流量池用户成功 userCode:{}, poolNums:{}, issueUserCode:{}", userCode, poolNums, issueUserCode);
        } else {
            issueUserCode = userDao.queryLBIssueUserPool3(userCode,customersUserEntity.getCustomerCode(), poolNums);
            logger.info("====LikeBackIssueTask-v5:获取流量池用户成功 userCode:{}, poolNums:{}, issueUserCode:{}", userCode, poolNums, issueUserCode);
        }

        if (StringUtils.isNotEmpty(issueUserCode)) {
            toUserCode = issueUserCode;
            List<String> userCodeList = new ArrayList<>();
            userCodeList.add(issueUserCode);
            issueUserDao.updateConnectCount(userCodeList);
        }

        if (toUserCode != null) {
            doLikeBack(userCode, toUserCode, app);
        }
    }

    public void doLikeBack(String userCode, String toUserCode, String app) {
        UserWlmEntity relation = userWlmDao.getRelation(userCode, toUserCode);
        if (relation == null) {
            return;
        }
        relation.setWlmType(LikeEnum.LIKE_EACH_OTHER.getType());
        if (relation.getConnectType() == 0) {
            relation.setConnectType(WLMType.LIKEBACK.getCode());
        }
        relation.setContactTime(new Date());
        relation.setLikesBackTime(new Date());
        userWlmDao.updateByPrimaryKey(relation);

        //新增likeback记录
        UserWlmEntity modelLikesBackRecord = new UserWlmEntity();
        modelLikesBackRecord.setLikesBackTime(new Date());
        modelLikesBackRecord.setContactTime(new Date());
        modelLikesBackRecord.setLikesTime(new Date());
        modelLikesBackRecord.setUserCode(toUserCode);
        modelLikesBackRecord.setUserCodeWlm(userCode);
        modelLikesBackRecord.setWlmType(LikeEnum.LIKE_EACH_OTHER.getType());
        modelLikesBackRecord.setConnectType(WLMType.LIKEBACK.getCode());
        userWlmDao.insert(modelLikesBackRecord);

        userWlmLogDao.addWlmLog(modelLikesBackRecord);

        addLikeBackRecord(userCode, toUserCode);

        try {
            pushNewMatchMessage(toUserCode, userCode, AppEnum.getEnumByUserAppFlat(app));
        } catch (Exception e) {
            logger.info("pushNewMatchMessage error: " + e.getMessage());
        }
    }

    private void addLikeBackRecord(String userCode, String toUserCode) {
        IssueLbRecordEntity issueLbRecordEntity = new IssueLbRecordEntity();
        issueLbRecordEntity.setUserCode(userCode);
        issueLbRecordEntity.setModelUserCode(toUserCode);
        UserEntity userEntity = userDao.selectByUserCode(toUserCode);
        issueLbRecordEntity.setOnlineStatus(userEntity.getOnline());
        issueLbRecordDao.insert(issueLbRecordEntity);
    }

    private void pushNewMatchMessage(String fromUserCode, String toUserCode, AppEnum appEnum) {
        pushEventBus.post(buildEvent(fromUserCode, toUserCode, appEnum));
    }


    private Event buildEvent(String fromUserCode, String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.MATCHED_PUSH.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUserCode).toUserCode(toUserCode).app(appEnum).content(JSONObject.toJSONString(params)).build();
    }

    /**
     * 判断当日是否有深度会话
     *
     * @param userCode
     * @return
     */
    public boolean ifConversationSure(String userCode) {
        boolean result = false;
        int count = userMsgSendTotalDao.getUserSendMsgCount(userCode);
        if (count > 0) {
            result = true;
        }
        return result;
    }

    public long distanceLikeBackTime(String userCode) {
        UserWlmEntity todayWlmRecord = userWlmDao.getLastLKRecord(userCode);
        if (todayWlmRecord == null || todayWlmRecord.getLikesBackTime() == null) {
            return 0;
        }
        return DateUtil.between(DateUtil.date(), todayWlmRecord.getLikesBackTime(), DateUnit.MINUTE);
    }

    /**
     * 未下发过的处理
     *
     * @param issueConfigEntity
     * @param userEntity
     */
    public void dealLikeOne(IssueConfigEntity issueConfigEntity, UserEntity userEntity, Boolean ifmMember) {
        logger.info("==likebackV5 喜欢数1个，likeback 0个 开始执行likeback 给用户:{} ifmMember:{} ==", userEntity.getUserCode(), ifmMember);
        boolean online = userEntity.getOnline() == 1;
        SimpleDateFormat format0 = new SimpleDateFormat("HHmmss");
        Time time = new Time(new Date().getTime());
        if (isToday(userEntity.getGmtModified())) {
            logger.info("==likebackV5 喜欢数1个，likeback 0个 用户今天有活跃 给用户:{} ifmMember:{} ==", userEntity.getUserCode(), ifmMember);
            push(userEntity.getUserCode(), ifmMember, userEntity.getAppCode());
        } else if (!online && Integer.parseInt(format0.format(issueConfigEntity.getIssueTime())) < Integer.parseInt(format0.format(time))) {
            //下发
            logger.info("==likebackV5 喜欢数1个，likeback 0个 ，不在线且时间在指定时间之后 给用户:{} ifmMember:{} ==", userEntity.getUserCode(), ifmMember);
            push(userEntity.getUserCode(), ifmMember, userEntity.getAppCode());
        }
    }

    /**
     * 已下发的处理
     *
     * @param issueConfigEntity
     * @param userEntity
     * @param likeBackCount
     */
    public void dealLikeMoreOne(IssueConfigEntity issueConfigEntity, UserEntity userEntity, Integer likeBackCount, Boolean ifmMember) {
        boolean online = userEntity.getOnline() == 1;
        if (online) {
            //用户在n分钟内，在聊会话数>=x个  才进行下发
            boolean conversationCount = ifConversationSure(userEntity.getUserCode());
            if (!conversationCount) {
                int issueTime = issueConfigEntity.getIssueOne() + (likeBackCount * issueConfigEntity.getIssueTwo());
                long distanceLikeBackTime = distanceLikeBackTime(userEntity.getUserCode());
                if (distanceLikeBackTime > issueTime) {
                    //下发
                    push(userEntity.getUserCode(), ifmMember, userEntity.getAppCode());
                }
            }
        } else if (isToday(userEntity.getGmtModified())) {
            int time = likeBackCount * issueConfigEntity.getIssueHour();
            long distanceLikeBackTime = distanceLikeBackTime(userEntity.getUserCode());
            if (distanceLikeBackTime > time) {
                //下发
                push(userEntity.getUserCode(), ifmMember, userEntity.getAppCode());
            }
        } else {
            SimpleDateFormat format0 = new SimpleDateFormat("HHmmss");
            Time time = new Time(new Date().getTime());
            if (Integer.parseInt(format0.format(issueConfigEntity.getIssueTime())) < Integer.parseInt(format0.format(time))) {
                int issueTime = likeBackCount * issueConfigEntity.getIssueHour();
                long distanceLikeBackTime = distanceLikeBackTime(userEntity.getUserCode());
                if (distanceLikeBackTime > issueTime) {
                    //下发
                    push(userEntity.getUserCode(), ifmMember, userEntity.getAppCode());
                }
            }
        }
    }

}
